<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品出库管理</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="/css/index.css">
    <!-- 引入组件库 -->
    <script src="/js/vue.js"></script>
    <script src="/js/index.js"></script>
    <script src="/js/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
        }
        .card-container {
            background: #fff;
            border-radius: 6px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
            margin-bottom: 20px;
            overflow: hidden;
        }
        .toolbar {
            padding: 16px 20px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 12px;
        }
        .filter-item {
            display: inline-block;
            margin-right: 10px;
        }
        .table-container {
            padding: 20px;
        }
        .el-table {
            border-radius: 4px;
            overflow: hidden;
        }
        .el-table th {
            background-color: #f7f8fa;
            font-weight: 500;
        }
        .el-table tr:hover > td {
            background-color: #fafafa !important;
        }
        .pagination-container {
            padding: 16px 20px;
            border-top: 1px solid #f0f0f0;
            text-align: right;
        }
        .status-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
            line-height: 1;
        }
        .status-pending {
            background-color: #fff2e8;
            color: #ff7d00;
        }
        .status-review {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        .status-passed {
            background-color: #e8f4ea;
            color: #00b42a;
        }
        .operation-buttons {
            display: flex;
            gap: 5px;
        }
        .dialog-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        .el-dialog__body {
            padding: 20px;
        }
        .el-form-item {
            margin-bottom: 18px;
        }
        .page-title {
            font-size: 18px;
            font-weight: 600;
            color: #1f2d3d;
            margin-bottom: 15px;
            padding-left: 20px;
            padding-top: 10px;
        }
        .date-container {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .date-label {
            color: #666;
            white-space: nowrap;
        }
        .pagination {
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .page-number {
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #d9d9d9;
            background: #fff;
            cursor: pointer;
        }
        .page-number:hover {
            border-color: #1890ff;
            color: #1890ff;
        }
        .page-number.active {
            background-color: #1890ff;
            color: white;
            border-color: #1890ff;
        }
        .ellipsis {
            padding: 0 5px;
            color: #666;
        }
    </style>
</head>
<body>
<div id="app">
    <h3 class="page-title">商品出库管理</h3>

    <!-- 主内容卡片 -->
    <div class="card-container">
        <!-- 添加/编辑商品对话框 -->
        <el-dialog
                title="添加出库记录"
                :visible.sync="dialogVisible"
                width="50%"
                :close-on-click-modal="false"
        >
            <el-form
                    :model="form"
                    ref="form"
                    label-width="100px"
                    :rules="formRules"
                    status-icon
            >
                <!-- 客户 -->
                <el-form-item label="客户" prop="customer">
                    <el-select
                            v-model="form.customer"
                            placeholder="请选择客户" clearable
                            style="width: 100%"
                    >
                        <el-option
                                v-for="customer in customerlist"
                                :key="customer.id"
                                :label="customer.customerName"
                                :value="customer.customerName"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <!-- 商品选择 -->
                <el-form-item label="商品" prop="productId">
                    <el-select v-model="form.productId" placeholder="请选择出库的商品" clearable>
                        <el-option
                                v-for="item in products"
                                :key="item.id"
                                :label="item.productName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <!-- 出库数量 -->
                <el-form-item label="数量" prop="quantity">
                    <el-input-number
                            v-model="form.quantity"
                            placeholder="请输入出库数量"
                            :min="1"
                            integer
                            controls-position="right"
                    ></el-input-number>
                </el-form-item>

                <!-- 单价 -->
                <el-form-item label="单价" prop="price">
                    <el-input-number
                            v-model="form.price"
                            :precision="2"
                            :step="0.01"
                            :min="0.01"
                            controls-position="right"
                            placeholder="请输入单价"
                    ></el-input-number>
                </el-form-item>

                <!-- 备注 -->
                <el-form-item label="备注" prop="remark">
                    <el-input
                            type="textarea"
                            v-model="form.remark"
                            placeholder="请输入备注信息（可选）"
                            rows="3"
                            maxlength="500"
                    ></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 工具栏 -->
        <div class="toolbar">
            <el-button type="primary" @click="showAddDialog" icon="el-icon-plus">
                添加出库信息
            </el-button>
            <el-input v-model="searchForm.id" placeholder="请输入出库ID" style="width: 200px;" class="filter-item"></el-input>
            <el-input v-model="searchForm.productName" placeholder="商品名称" style="width: 200px;" class="filter-item"></el-input>

            <!-- 新增创建日期搜索 -->
            <div class="date-container">
                <span class="date-label">创建日期:</span>
                <el-date-picker
                        v-model="searchForm.createTime"
                        type="date"
                        placeholder="选择创建日期"
                        value-format="yyyy-MM-dd"
                        style="width: 200px;"
                ></el-date-picker>
            </div>

            <el-button type="primary" @click="loadData" icon="el-icon-search">
                查询
            </el-button>
            <el-button type="warning" @click="batchStockOut" icon="el-icon-check">
                批量提交
            </el-button>
            <el-button @click="resetSearch" icon="el-icon-refresh">
                重置
            </el-button>
        </div>

        <!-- 数据表格 -->
        <div class="table-container">
            <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    highlight-current-row>
                <!-- 勾选框列（第一列） -->
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="productName" label="产品名" width="120"></el-table-column>
                <el-table-column prop="quantity" label="出库数量" width="100"></el-table-column>
                <el-table-column prop="price" label="单价" width="100" :formatter="formatPrice"></el-table-column>
                <el-table-column prop="amount" label="总金额" width="100" :formatter="formatPrice"></el-table-column>
                <el-table-column prop="customer" label="客户" width="140"></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                    <template slot-scope="{row}">
                        <span :class="getStatusCode(row.status)">{{ getStatusText(row.status) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="160"></el-table-column>
                <el-table-column prop="completeTime" label="出库时间" width="160"></el-table-column>
                <el-table-column prop="remark" label="备注" min-width="120"></el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <div class="operation-buttons">
                            <el-button size="mini" type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status !== 1">
                                提交审核
                            </el-button>
                            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                                删除
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            dialogVisible: false,
            form: {
                customer: '',
                productId: null,
                quantity: 1,
                price: 0.01,
                remark: ''
            },
            selectedRows: [], // 存储选中的行数据
            formRules: {
                customer: [
                    { required: true, message: '请选择客户名称', trigger: 'change' }
                ],
                productId: [
                    { required: true, message: '请选择出库商品', trigger: 'change' }
                ],
                quantity: [
                    { required: true, message: '请输入出库数量', trigger: 'blur' },
                    { type: 'number', min: 1, message: '出库数量必须大于0', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入单价', trigger: 'blur' },
                    { type: 'number', min: 0.01, message: '单价必须大于0', trigger: 'blur' }
                ]
            },
            products: [],
            customerlist: [],
            searchForm: {
                productName: '',
                id: '',
                createTime: '' // 单个创建日期，格式YYYY-mm-dd
            },
            tableData: [],
            pageNum: 1,
            pageSize: 10,
            total: 0
        },
        created() {
            this.loadData();
            this.loadCategories();
            this.loadCatecustomer();
        },
        methods: {
            // 格式化价格
            formatPrice(row, column, value) {
                return value ? '¥' + parseFloat(value).toFixed(2) : '¥0.00';
            },

            // 获取状态文本
            getStatusText(status) {
                switch(status) {
                    case 1: return '未出库';
                    case 2: return '待审核';
                    case 0: return '已出库';
                    default: return '未知状态';
                }
            },

            // 获取状态样式
            getStatusCode(status) {
                switch(status) {
                    case 1: return 'status-tag status-pending';
                    case 2: return 'status-tag status-review';
                    case 0: return 'status-tag status-passed';
                    default: return 'status-tag';
                }
            },

            // 监听勾选框变化，同步选中项到 selectedRows
            handleSelectionChange(selection) {
                this.selectedRows = selection;
            },

            // 批量出库逻辑
            batchStockOut () {
                // 1. 检查是否有选中项
                if (this.selectedRows.length === 0) {
                    this.$message.warning("请先勾选需要提交出库的记录");
                    return;
                }

                // 2. 筛选未出库的记录（status=1表示未出库）
                const unprocessed = this.selectedRows.filter(row => row.status === 1);
                if (unprocessed.length === 0) {
                    this.$message.info("选中的记录均已出库或待审核");
                    return;
                }

                // 3. 提取未出库记录的outId列表
                const stockOutDetails = unprocessed.map(row => ({outId: row.outId}));

                // 4. 批量提交审核
                axios.put("/stockOut/batch", stockOutDetails)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.$message.success("批量提交成功");
                            this.loadData(); // 刷新表格
                        } else {
                            this.$message.error("批量提交失败：" + response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('提交失败:', error);
                        this.$message.error('系统错误');
                    });
            },

            // 显示添加对话框
            showAddDialog() {
                this.dialogVisible = true;
                // 重置表单
                this.$nextTick(() => {
                    if (this.$refs.form) {
                        this.$refs.form.resetFields();
                    }
                    this.form = {
                        customer: '',
                        productId: null,
                        quantity: 1,
                        price: 0.01,
                        remark: ''
                    };
                });
            },

            // 提交表单
            submitForm() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        axios.post('/stockOut/insertSatockOut', this.form)
                            .then(response => {
                                if (response.data.code === 200) {
                                    this.$message.success('出库记录添加成功！');
                                    this.dialogVisible = false;
                                    this.loadData(); // 刷新列表数据
                                } else {
                                    this.$message.error(response.data.msg || '添加失败，请重试');
                                }
                            })
                            .catch(error => {
                                console.error('提交失败:', error);
                                this.$message.error('系统错误，添加失败');
                            });
                    }
                });
            },

            // 加载数据（包含创建日期筛选）
            loadData() {
                const params = {
                    pageNo: this.pageNum,
                    pageSize: this.pageSize,
                    data: {
                        productName : this.searchForm.productName,
                        id : this.searchForm.id,
                        createTime: this.searchForm.createTime // 新增：创建日期参数
                    }
                };

                axios.post('/stockOut/list', params)
                    .then(response => {
                        if (response.data.code === 200) {
                            this.tableData = response.data.data.list || [];
                            this.total = response.data.data.total || 0;
                        } else {
                            this.$message.error(response.data.msg || '加载数据失败');
                        }
                    })
                    .catch(error => {
                        console.error('请求错误:', error);
                        this.$message.error('系统错误');
                    });
            },

            // 重置搜索条件
            resetSearch() {
                this.searchForm = {
                    productName: '',
                    id: '',
                    createTime: '' // 清空日期搜索
                };
                this.pageNum = 1;
                this.loadData();
            },

            // 加载商品数据
            loadCategories() {
                axios.post('/product/list')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.products = response.data.data.list || [];
                        } else {
                            this.$message.error(response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        this.$message.error('系统错误');
                    });
            },

            // 加载客户数据
            loadCatecustomer() {
                axios.post('/customer/listStatus')
                    .then(response => {
                        if (response.data.code === 200) {
                            this.customerlist = response.data.data || [];
                        } else {
                            this.$message.error(response.data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        this.$message.error('系统错误');
                    });
            },

            // 处理页码变化
            handleCurrentChange(val) {
                this.pageNum = val;
                this.loadData();
            },

            // 处理每页条数变化
            handleSizeChange(val) {
                this.pageSize = val;
                this.pageNum = 1; // 重置到第一页
                this.loadData();
            },

            // 处理编辑（提交审核）
            handleEdit(row) {
                this.$confirm('确认要提交该商品的出库信息吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.put('/stockOut/update', row)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('提交成功，请等待审核结果');
                                this.loadData();
                            } else {
                                this.$message.error(response.data.msg);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            this.$message.error('系统错误');
                        });
                }).catch(() => {
                    this.$message.info('已取消操作');
                });
            },

            // 处理删除
            handleDelete(row) {
                this.$confirm('确认删除该出库记录吗？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'error'
                }).then(() => {
                    axios.get('/stockOut/delete/' + row.outId)
                        .then(response => {
                            if (response.data.code === 200) {
                                this.$message.success('删除成功');
                                this.loadData();
                            } else {
                                this.$message.error(response.data.msg);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            this.$message.error('系统错误');
                        });
                }).catch(() => {
                    this.$message.info('已取消删除');
                });
            }
        }
    });
</script>
</body>
</html>